<?php
/**
 * http请求类
 *
 * @author Mo yi <root@imoi.cn>
 * @link   http://www.imoi.cn
 * @copyright Copyright &copy; 2010-2012 DuoLam Software LLC
 * @license http://www.imoi.cn/license/
 * @version $Id: dpRequest.php 2799 2012-04-04 13:35:54Z Mo.yi $
 * @package system
 * @since 1.0
 */
class dpRequest
{

	private $_hostInfo;

	/**
     * HTTP状态信息数组
     *
     * @var array
     */
    protected $httpStatus = array(

        '100' => 'Continue',
        '101' => 'Switching Protocols',

        '200' => 'OK',
        '201' => 'Created',
        '202' => 'Accepted',
        '203' => 'Non-Authoritative Information',
        '204' => 'No Content',
        '205' => 'Reset Content',
        '206' => 'Partial Content',

        '300' => 'Multiple Choices',
        '301' => 'Moved Permanently',
        '302' => 'Found',
        '303' => 'See Other',
        '304' => 'Not Modified',
        '305' => 'Use Proxy',
        '306' => '(Unused)',
        '307' => 'Temporary Redirect',

        '400' => 'Bad Request',
        '401' => 'Unauthorized',
        '402' => 'Payment Required',
        '403' => 'Forbidden',
        '404' => 'Not Found',
        '405' => 'Method Not Allowed',
        '406' => 'Not Acceptable',
        '407' => 'Proxy Authentication Required',
        '408' => 'Request Timeout',
        '409' => 'Conflict',
        '410' => 'Gone',
        '411' => 'Length Required',
        '412' => 'Precondition Failed',
        '413' => 'Request Entity Too Large',
        '414' => 'Request-URI Too Long',
        '415' => 'Unsupported Media Type',
        '416' => 'Requested Range Not Satisfiable',
        '417' => 'Expectation Failed',

        '500' => 'Internal Server Error',
        '501' => 'Not Implemented',
        '502' => 'Bad Gateway',
        '503' => 'Service Unavailable',
        '504' => 'Gateway Timeout',
        '505' => 'HTTP Version Not Supported',
    );

	/**
	 * 获取当前应用程序域名
	 */
	public function getHostInfo($schema='')
	{
		if ($this->_hostInfo===null) {
			if ($secure=$this->getIsSecureConnection())
				$http='https';
			else
				$http='http';
			if (isset($_SERVER['HTTP_HOST']))
				$this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
			else {
				$this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
				$port=$secure ? $this->getSecurePort() : $this->getPort();
				if(($port!==80 && !$secure) || ($port!==443 && $secure))
					$this->_hostInfo.=':'.$port;
			}
		}

		if ($schema!=='') {
			$secure=$this->getIsSecureConnection();
			if ($secure && $schema==='https' || !$secure && $schema==='http')
				return $this->_hostInfo;

			$port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
			if ($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
				$port=':'.$port;
			else
				$port='';

			$pos=strpos($this->_hostInfo,':');
			return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
		}
		else
			return $this->_hostInfo;
	}

	/**
	 * 检测是否是https连接模式
	 */
	public function getIsSecureConnection()
	{
		return isset($_SERVER['HTTPS']) && !strcasecmp($_SERVER['HTTPS'],'on');
	}

	/**
	 * 获取安全端口 443 https
	 */
	public function getSecurePort()
	{
		return $this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
	}
	
	/**
	 * 获取普通端口 80 http
	 */
	public function getPort()
	{
		return $this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
	}

	/**
	 * 检测是否是ajax通信
	 */
	public function getIsAjaxRequest()
	{
		return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
	}

	/**
     * 获取客户端系统语言
     *
     * @access public
     * @return string
     */
    public function getUserLang()
	{
        return isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? htmlspecialchars($_SERVER['HTTP_ACCEPT_LANGUAGE']) : '';
    }

    /**
     * 获取客户端IP
     *
     * @access public
     * @return string
     */
    public static function getUserIp()
	{
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
			$ip = getenv("HTTP_CLIENT_IP");
		else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
			$ip = getenv("HTTP_X_FORWARDED_FOR");
		else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
			$ip = getenv("REMOTE_ADDR");
		else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
			$ip = $_SERVER['REMOTE_ADDR'];
		else
			$ip = "unknown";
		return $ip;
    }

    /**
     * 获取当前页面的url来源
     *
     * @access public
     * @return string
     */
    public function getUrlSource()
	{
        return isset($_SERVER['HTTP_REFERER']) ? htmlspecialchars($_SERVER['HTTP_REFERER']) : null;
    }

    /**
     * 获取客户端浏览器信息
     *
     * @access public
     * @return string
     */
    public static function getUserBrowser()
	{

        $user_agent_info = htmlspecialchars($_SERVER['HTTP_USER_AGENT']);

        if (strpos($user_agent_info,'MSIE 9.0'))
            return 'IE9';
        else if (strpos($user_agent_info,'MSIE 8.0'))
            return 'IE8';
        else if (strpos($user_agent_info,'MSIE 7.0'))
            return 'IE7';
        else if (strpos($user_agent_info,'MSIE 6.0'))
            return 'IE6';
        else if (strpos($user_agent_info,'Firefox'))
            return 'Firfox';
        else if (strpos($user_agent_info,'Chrome'))
            return 'Chrome';
        else if (strpos($user_agent_info,'Opera'))
            return 'Opera';
        else if (strpos($user_agent_info,'Safari'))
            return 'Safari';
        else if (strpos($user_agent_info,'Elinks'))
            return 'Elinks';
        else if (strpos($user_agent_info,'OmniWeb'))
            return 'OmniWeb';
        else if (strpos($user_agent_info,'Links'))
            return 'Links';
        else if (strpos($user_agent_info,'Lynx'))
            return 'Lynx';
        else if (strpos($user_agent_info,'Arora'))
            return 'Arora';
        else if (strpos($user_agent_info,'Epiphany'))
            return 'Epiphany';
        else if (strpos($user_agent_info,'Konqueror'))
            return 'Konqueror';
        else if (strpos($user_agent_info,'EudoraWeb'))
            return 'EudoraWeb';
        else if (strpos($user_agent_info,'Minimo'))
            return 'Minimo';
        else if (strpos($user_agent_info,'NetFront'))
            return 'NetFront';
        else if (strpos($user_agent_info,'POLARIS'))
            return 'Polaris';
        else if (strpos($user_agent_info,'BlackBerry'))
            return 'BlackBerry';
        else if (strpos($user_agent_info,'Nokia'))
            return 'Nokia';
        else
            return 'Others';
    }

    /**
     * 获取客户端操作系统信息
     *
     * @access public
     * @return string
     */
    public static function getUserOs()
	{
        $user_agent_info = htmlspecialchars($_SERVER['HTTP_USER_AGENT']);
        if (strpos($user_agent_info,'Windows NT 6.1'))
            return 'Windows 7';
        else if (strpos($user_agent_info,'Windows NT 6.0'))
            return 'Windows Vista';
        else if (strpos($user_agent_info,'Windows NT 5.2'))
            return 'Windows 2003';
        else if (strpos($user_agent_info,'Windows NT 5.1'))
            return 'Windows XP';
        else if (strpos($user_agent_info,'Windows NT 5.0'))
            return 'Windows 2000';
        else if (strpos($user_agent_info,'Windows ME'))
            return 'Windows ME';
        else if (strpos($user_agent_info,'Windows Phone'))
            return 'Windwos Phone';
        else if (strpos($user_agent_info,'Android'))
            return 'Android';
        else if (strpos($user_agent_info,'iPhone'))
            return 'iPhone OS';
        else if (strpos($user_agent_info,'iOS'))
            return 'iPhone OS';
        else if (strpos($user_agent_info,'Symbian OS'))
            return 'Symbian';
        else if (strpos($user_agent_info,'PPC Mac OS X'))
            return 'OS X PPC';
        else if (strpos($user_agent_info,'Intel Mac OS X'))
            return 'OS X Intel';
        else if (strpos($user_agent_info,'Win98'))
            return 'Windows 98';
        else if (strpos($user_agent_info,'Win95'))
            return 'Windows 95';
        else if (strpos($user_agent_info,'WinNT4.0'))
            return 'Windows NT4.0';
        else if (strpos($user_agent_info,'Mac OS X Mach-O'))
            return 'OS X Mach';
        else if (strpos($user_agent_info,'Ubuntu'))
            return 'Ubuntu';
        else if (strpos($user_agent_info,'Debian'))
            return 'Debian';
        else if (strpos($user_agent_info,'AppleWebKit'))
            return 'WebKit';
        else if (strpos($user_agent_info,'Mint/8'))
            return 'Mint 8';
        else if (strpos($user_agent_info,'Minefield'))
            return 'Minefield Alpha';
        else if (strpos($user_agent_info,'gentoo'))
            return 'Gentoo';
        else if (strpos($user_agent_info,'Kubuntu'))
            return 'Kubuntu';
        else if (strpos($user_agent_info,'Slackware/13.0'))
            return 'Slackware 13';
        else if (strpos($user_agent_info,'Fedora'))
            return 'Fedora';
        else if (strpos($user_agent_info,'FreeBSD'))
            return 'FreeBSD';
        else if (strpos($user_agent_info,'SunOS'))
            return 'SunOS';
        else if (strpos($user_agent_info,'OpenBSD'))
            return 'OpenBSD';
        else if (strpos($user_agent_info,'NetBSD'))
            return 'NetBSD';
        else if (strpos($user_agent_info,'DragonFly'))
            return 'DragonFly';
        else if (strpos($user_agent_info,'IRIX'))
            return 'IRIX';
        else if (strpos($user_agent_info,'Windows CE'))
            return 'Windows CE';
        else if (strpos($user_agent_info,'PalmOS'))
            return 'PalmOS';
        else if (strpos($user_agent_info,'Linux'))
            return 'Linux';
        else if (strpos($user_agent_info,'DragonFly'))
            return 'DragonFly';
        else if (strpos($user_agent_info,'Mac OS X'))
            return 'Mac OS X';
        else if (strpos($user_agent_info,'Symbian OS'))
            return 'Symbian';
        else if (strpos($user_agent_info,'SymbianOS'))
            return 'SymbianOS';
        else if (strpos($user_agent_info,'webOS'))
            return 'webOS';
        else if (strpos($user_agent_info,'PalmSource'))
            return 'PalmSource';
        else
            return 'Others';
    }

    /**
     * 检测用户是否是移动端设备
     */
    public static function isMobileTerminal()
    {
        $uachar = "/(nokia|sony|ericsson|mot|samsung|sgh|lg|philips|panasonic|alcatel|lenovo|cldc|midp|mobile|symbian|windowsphone|windows\sphone|ios|android|blackberry)/i";
        if (!empty($_SERVER['HTTP_USER_AGENT']) && preg_match($uachar, $_SERVER['HTTP_USER_AGENT'])) {
            return true;
        } else {
            return false;
        }
    }

	public static function download($file, $rename = NULL, $isLarge = FALSE)
	{

        if (headers_sent())return false;

        if (!$file) {
            exit('Error 404:The file not found!');
        }

        if ($rename==NULL) {
            if (strpos($file, '/')===FALSE && strpos($file, '\\')===FALSE)
                $filename = $file;
            else
                $filename = basename($file);
        }
		else
        {
            $filename = explode(DS, $file);
            $file_tmp = $filename[count($filename)-1];
            $filename = preg_replace('/(\w+)\.(\w+)/i', $rename.'.\\2', $file_tmp);
        }
        $rs = fopen($file, 'r');
        header('Content-Type:text/html;charset=utf-8');
        header('Content-Description: File Transfer');
        header("Accept-Ranges: bytes"); 
        header('Content-Type: application/octet-stream');
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        echo fread($rs, filesize($file));
        fclose($file);
        exit;
    }

    /**
     * Read a file and display its content chunk by chunk
     *
     * @param string $filename
     * @param bool $retbytes
     * @return mixed
     */
    private function _readfileChunked($filename, $retbytes = TRUE, $chunk_size = 1024)
	{

        $buffer = '';
        $cnt =0;

        $handle = fopen($filename, 'rb');
        if ($handle === false) {
            return false;
        }
        while (!feof($handle)) {
            $buffer = fread($handle, $chunk_size);
            echo $buffer;
            ob_flush();
            flush();
            if ($retbytes) {
                $cnt += strlen($buffer);
            }
        }
        $status = fclose($handle);
        if ($retbytes && $status) {
            return $cnt;
        }
        return $status;
    }

    /**
     * 设置HTTP状态信息
     *
     * @access public
     * @param string $code  HTTP 状态编码
     * @param string $name  HTTP 状态信息
     * @return string
     */
    public function httpStatus($code, $text = null)
	{
        $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
        $text = is_null($text) ? $this->httpStatus[$code] : $text;
        $status = "$protocol $code $text";
        header($status);
    }


    /**
     * 获取变量结果
     *
     */
    public function value($name, $default='')
    {
        if (!empty($_POST[$name])) return $_POST[$name];
        if (empty($_GET[$name]) && $default !='') $default;
        else if (empty($_GET[$name])) return null;
        else return $_GET[$name];
    }
}
?>